const config = require('../config.js')
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//将发表内容同步到服务器
const uploadNote = (note,cb) => {

  const content = note.content
  const address = note.address
  const addr_name = note.addr_name
  const longitude = note.longitude
  const latitude = note.latitude
  const images = note.images
  const personal = note.personal
  const timestamp = note.timestamp;
  const userInfo = note.userInfo;

  //异步图片上传任务
  // const tasks = [];
  // const upload = function(path, i) {
  //   return new Promise((resolve, reject) => {
  //     wx.uploadFile({
  //       url: 'https://wechat.forsomething.cn/wx/upload', //仅为示例，非真实的接口地址
  //       filePath: path,
  //       name: 'file',
  //       formData: {
  //         'user': 'test',
  //         'index': i + ''
  //       },
  //       success: function (res) {
  //         var data = res.data
  //         // console.log('success!');
  //         resolve(res.data);
  //       },
  //       fail: function (res) {
  //         console.log('fail!');
  //         reject('fail!')
  //       }
  //     })
  //   })
  // }
  // //上传所有图片
  // if (images.length > 0) {
  //   for (let i = 0; i < images.length; i++) {
  //     tasks.push(upload(images[i], i));
  //   }
  // } else {
  //   console.log('no images');
  // }
  // if (tasks.length>0){
  //   Promise.all(tasks);
  // }
  //保存note信息
  var pics = note.images;
  delete note.images;
  var msgReq = { 'messageDTO': note, 'picDTOS': pics}
  wx.request({
    url: config.saveNoteUrl,
    method: 'POST',
    data: msgReq,
    header: {
      'content-type': 'application/json' // 默认值
    },
    success: function (res) {
      //不管服务器返回的状态码是200还是500，都会执行success函数，大坑之一
      //所以接口返回数据必须有state字段标识请求是否成功
      var data = res.data
      console.log(data)
      if (data.state){
        console.log('save success');
        cb && cb(note, true);
      }else{
        console.log('save faild');
        cb && cb(note, false);
      }
    }
  })
} 

// //对象数组排序工具
// var compare = function (prop) {
//   return function (obj1, obj2) {
//     var val1 = obj1[prop];
//     var val2 = obj2[prop];
//     if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
//       val1 = Number(val1);
//       val2 = Number(val2);
//       return (val2 - val1)
//     }
   
//   }
// }
module.exports = {
  formatTime: formatTime,
  uploadNote: uploadNote
  // compare: compare
}
